#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv){

    for (int i =0; i<argc; i++){
        printf("%s \n", argv[i]);
    }
    
    if(argc != 6) {
        fprintf(stdout, "Usage: ./cut_yuv ./xxx.yuv start stop width height \n");
        fprintf(stderr, "Must input 6 parameters\n");
        return -1;
    }
    
    char *input_filename = NULL;
    char output_filename[100];
    int start = 0;
    int stop = 0;
    int width = 0;
    int height = 0;
    int frame_num = 0;
    int frame_size = 0;
    int file_size = 0;
    FILE *infp = NULL;
    FILE *outfp = NULL;

    input_filename = argv[1];
    start = atoi(argv[2]);
    stop = atoi(argv[3]);
    width = atoi(argv[4]);
    height = atoi(argv[5]);

    infp = fopen(input_filename, "rb");
    if (infp == NULL){
        fprintf(stderr, "open file %s failed !\n", input_filename);   
    }

    sprintf(output_filename, "%s_%d_%d_%d_%d.yuv", argv[1], start, stop, width, height);

    outfp = fopen(output_filename, "wb");
    if (outfp == NULL){
        fprintf(stderr, "open file %s failed! \n", output_filename);
        return -1;
    }

    frame_size = width*height*3/2;
    unsigned char *buffer = (unsigned char *) malloc(frame_size * sizeof(unsigned char));
    if(buffer == NULL){
        fprintf(stderr, "malloc return null! \n");
        return -1;
    }

    fseek(infp, 0, SEEK_END);
    file_size = ftell(infp);
    frame_num = file_size/frame_size;
    fprintf(stdout, "Input file: %s total has %d frames \n", argv[1], frame_num);
    if(start >= stop || start > frame_num || stop >frame_num){
        fprintf(stderr, "please check the start stop! \n");
        goto fail;
    }
    
    fseek(infp, (start-1)*frame_size, SEEK_SET);
    int i = 0;
    while(i<=stop){
        if(fread(buffer, 1, frame_size, infp) == frame_size){
            fwrite(buffer, 1, frame_size, outfp);
        }else{
            break;
        }
        i++;
    }
    fprintf(stdout, "Complete! \n");
fail:
    fclose(infp);
    fclose(outfp);
    free(buffer);
    buffer = NULL;
    return 0;
}